package com.lingxu.traffic.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lingxu.api.utils.JSONArrayToListConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: ptmh
 * @ClassName AipUtils
 * @description:
 * @author: gxy
 * @create: 2025-07-15 16:02
 * @Version 1.0
 **/
@Slf4j
public class ApiUtils {

    private static final String SUCCESS_CODE = "0";

    /**
     * 构建接口请求报文
     * {
     * 			"page": {	//分页，可选，默认500每页，默认在第一页
     * 				"currentPage": 1,
     * 				"pageSize": 500,		//分页大小，默认为500，最大为500
     * 				"sortColumns": {
     * 					"字段A": "ASC"		//此为排序依据，可使用返回字段中
     *                                }
     *           },
     * 			"userInfo": {
     * 				"departmentCode": "0123456789045678U",	//部门代码
     * 				"tokenCode": "1234567890"		//token,需换成对应接口的token
     *            },
     * 			"params": {
     * 				"必要字段A": { 		//必要参数，没有就报错
     * 					"value": "12345"		//固定值，使用 value
     *                },
     * 				"可选字段B": { 		//可选参数，可有可无
     * 					"value": "1234"
     *                }
     *            }
     * }
     * @param pageNo 页号
     * @param pageSize 每页数量 接口限定最大500
     * @param orgCode 组织编码
     * @param token 认证token
     * @param params 查询条件
     * @param sortInfo 排序规则
     * @return
     */
    public static JSONObject buildJsonData(Integer pageNo,Integer pageSize,String orgCode,String token,JSONObject params,JSONObject sortInfo) {
        JSONObject page = new JSONObject();
        page.put("currentPage", pageNo++);
        page.put("pageSize", pageSize);
        if(null!=sortInfo) {
            page.put("sortColumns", sortInfo);//排序规则
        }
        // 1. 权限信息（必须保留，否则无权限访问）
        JSONObject userInfo = new JSONObject();
        userInfo.put("departmentCode", orgCode);
        userInfo.put("tokenCode", token);
        // 2. 整合完整参数
        JSONObject jsonData = new JSONObject();
        jsonData.put("page", page);        // 分页信息
        jsonData.put("userInfo", userInfo);// 权限信息
        jsonData.put("params", null==params?new JSONObject():params);//空查询条件
        return jsonData;
    }

    public static String getDate(String url,String jsonData) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        String result = null;
        try {
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("jsonData", jsonData));
            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    log.info("接口{},HTTP错误: ",url,statusCode);
                } else {
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            }
        } catch (Exception e) {
            log.info("接口{} 调用异常: ",url,e);
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static JSONArray parseResult(String result) {
        try {
            JSONObject responseJson = JSONObject.parseObject(result);
            JSONObject resultObj = responseJson.getJSONObject("result");
            String code = resultObj.getString("code");
            if (SUCCESS_CODE.equals(code)) {
                return responseJson.getJSONArray("datas");
            }
        } catch (Exception e) {
            log.info("解析结果异常：", e);
        }
        return null;
    }

    /**
     * 通用api接口数据获取
     * @param url 接口url
     * @param token 接口token
     * @param orgCode 接口组织编码
     * @param pageNo 页号
     * @param pageSize 每页大小
     * @param params 查询规则
     * @param sortInfo 排序规则
     * @param targetType 数据集类型
     * @return
     */
    public static <T> List<T> getApiData(String url,String token,String orgCode,Integer pageNo,Integer pageSize,JSONObject params,JSONObject sortInfo, Class<T> targetType) {
        List<T> res = new ArrayList<>();
        JSONObject jsonObject = ApiUtils.buildJsonData(pageNo,pageSize,orgCode,token,params,sortInfo);
        log.info("接口：{},请求报文：{}",url,jsonObject);
        String resBody = ApiUtils.getDate(url, jsonObject.toJSONString());
        log.info("接口：{},成功返回结果",url);
        if(null==resBody) {
            return res;
        }
        JSONArray array = ApiUtils.parseResult(resBody);
        if(CollectionUtils.isEmpty(array)) {
            return res;
        }
        try {
            res = JSONArrayToListConverter.convert(array, targetType);
        } catch (Exception e) {
            log.info("构建接口{},数据异常",url,e);
        }
        return res;
    }

}
